import api from '../common/api.js'
import store from '../store/global.js'
import util from '../utils/index.js'
const request = ({
	url = '',
	data = {},
	type = 'GET',
	header = {}
}) => {
	return new Promise((resolve, reject) => {

		let token = store.state.token
		if (token) {
			header.Apitoken = token;
		}
		uni.request({
			method: type,
			url: api.HTTP_URL + url,
			data: data,
			header: header,
			dataType: 'json',
			enableCookie: true,
			withCredentials: false,
			success: suc => {

				if (suc.statusCode == 500) {
					uni.showToast({
						title: '系统错误，请联系管理员',
						icon: "none"
					});

					return false;
				}
				let res = suc.data
				if (res.code == 200) {
					resolve(res);

				} else if (res.code == 401) {

					// 假设401为token失效，这里跳转登录
					uni.showToast({
						title: res.msg || "默认提示",
						icon: "none",
					});
					setTimeout(() =>{
						handleLogin();
					},1000);

					
					// setTimeout(() => {
					// 	// 此为uView的方法，详见路由相关文档
					// 	// uni.reLaunch({
					// 	// 	url: '/pages/login/login'
					// 	// })
					// }, 1500)
					return false;
				} else {
					uni.showToast({
						title: res.msg || "服务器繁忙" ,
						icon: "none"
					});
					return false;
				}
			},
			fail: err => {
				reject(err)
			},
		})

	});
};
const handleLogin = function(){
	const fullPath = util.currFullPath();
	if (fullPath.indexOf("login") > -1) return;
	const url = `/pages/login/login${fullPath ? `?url=${fullPath}` : ""}`;
	console.log(url);
	setTimeout(() => {
	    uni.navigateTo({ url });
	}, 200);
}


const nav = function(type, url) {
	if (type == '2') {
		uni.navigateBack({
			delta: 1
		})
		return
	}
	if (type == '1') {
		uni.navigateTo({
			url: url
		})
		return
	}

};

export default {
	nav,
	request,
	handleLogin
}
